from functools import wraps


class TempMailException(Exception):
    def __init__(self, error_name, error_description, *args, **kwargs):
        super(TempMailException, self).__init__(
            "[{}]{}".format(error_name, error_description)
        )
        self.error_name = error_name
        self.error_description = error_description

    def __str__(self):
        return "[{}]{}".format(self.error_name, self.error_description)


def check_response():
    def checker(f):
        @wraps(f)
        async def wrap(*args, **kwargs):
            rf = await f(*args, **kwargs)
            if type(rf) == dict:
                if not rf.get("error"):
                    return rf
                else:
                    raise TempMailException(
                        error_name="Invalid response",
                        error_description=rf["error"][0]["message"],
                    )
            else:
                raise TempMailException(
                    error_name="Invalid response",
                    error_description="Server returned text, but not json",
                )

        return wrap

    return checker
